//
//  JigSawFeedbackView.m
//  JigSawKiosk
//
//  Created by Stulberg on 10-10-17.
//  Copyright 2010 FruitonLabs. All rights reserved.
//

#import "JigSawFeedbackView.h"


extern int kRecordTime ;

extern NSString* kGraphicsPath ;
extern NSString* kWatchSelectedImage ;
extern NSString* kRecordGreenImage ;
extern NSString* kWatchUnselectedImage ;
extern NSString* kRecordRedImage ;
extern NSString* kMovieRecordPath ;
 

@interface JigSawFeedbackView (internal)
- (CGPoint) mapMouse:(CGPoint) inPoint inRect:(CGRect) inRect ;
@end

@implementation JigSawFeedbackView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
		canEdit = YES ;
		editing = NO ;
		commenting = NO ;
		isRecording = NO ;
		timeValue = kRecordTime ;
		[self setPathToRecordTo: @"no video recorded"];
		[self setupLayers] ;
		currentMovieName = @"" ;
		[[self window] setIgnoresMouseEvents:YES] ;
		
		
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
	[[NSColor clearColor] setFill];
    NSRectFill(dirtyRect);
}


#pragma mark Delegate 
/* ---------------------------------
	Our delegate methods
 ---------------------------------*/

- (void)setDelegate:(id)aDelegate {
	// not retained
	delegate = aDelegate;
}

// call this function to notify meta view that we have finished
- (void)delegatedMethod {
	[delegate feedBackCallback:self] ;
}


- (void) keyUp: (NSEvent *) event
{
    NSString *characters;
    characters = [event characters];
	
    unichar character;
    character = [characters characterAtIndex: 0];
	
	
	// runaway when eneter is pressed and I am commenting
	// enter
	if (character == 13) {
		if ([self isCommenting] && [self isEditing] && canEdit) {
			[self saveFeedbackLogEntry];
			[self startFinishTimer] ;
		}
	}
	
	// s or S
	if (character == 115 || character == 83) {
		if (isRecording && canEdit) {
			[self toggleRecord] ;
			//canEdit = NO ;
		}
	}

	
	// a or A
	if (character == 97 || character == 65 ) {
		if (isRecording && canEdit) {
			[self toggleRecord] ;
			//canEdit = NO ;
		}
	}
	
}

#pragma mark start stop record session

- (void) stopRecordPreview {
	[recordView stopSession] ;
}
- (void) startRecordPreview {
	[recordView startSession] ;
}

#pragma mark mouse events
- (void)mouseEntered:(NSEvent *)theEvent {
	//printf("LLLLLLLLL");
	
}
- (void)mouseIn:(NSPoint)loc
{
	//
	//NSPoint  loc = [self convertPoint: [event locationInWindow] fromView: nil];	
	//CGPoint cgloc = NSPointToCGPoint(loc) ;
	//if(kRotate) {
		
		if(canEdit) {
			
			if([nameField hitTest:loc]) {
				[[self window] makeFirstResponder:nil] ;
				[emailField setSelectable:NO] ;
				[commentField setSelectable:NO] ;
				[emailField setEditable:NO] ;
				[commentField setEditable:NO] ;
				
				//[emailField setAllowsEditingTextAttributes:NO] ;
				//[commentField setAllowsEditingTextAttributes:NO] ;
				
				[nameField setSelectable:YES] ;
				[nameField setEditable:YES] ;
				[[self window] makeFirstResponder:nameField] ;
				
			}
			if([emailField hitTest:loc]) {
				[[self window] makeFirstResponder:nil] ;
				[nameField setSelectable:NO] ;
				[commentField setSelectable:NO] ;
				[nameField setEditable:NO] ;
				[commentField setEditable:NO] ;
				
				//[nameField setAllowsEditingTextAttributes:NO] ;
				//[commentField setAllowsEditingTextAttributes:NO] ;
				
				[emailField setSelectable:YES] ;
				[emailField setEditable:YES] ;
				[[self window] makeFirstResponder:emailField] ;
			}
			if([commentField hitTest:loc]) {
				[[self window] makeFirstResponder:nil] ;
				[nameField setSelectable:NO] ;
				[emailField setSelectable:NO] ;
				[nameField setEditable:NO] ;
				[emailField setEditable:NO] ;
				
				//[nameField setAllowsEditingTextAttributes:NO] ;
				//[commentField setAllowsEditingTextAttributes:NO] ;
				
				[commentField setSelectable:YES] ;
				[commentField setEditable:YES] ;
				[[self window] makeFirstResponder:commentField] ;
			}
			
			if([recordButtonView hitTest:loc]) {
				
				[nameField setSelectable:NO] ;
				[emailField setSelectable:NO] ;
				[commentField setSelectable:NO] ;
				[nameField setEditable:NO] ;
				[emailField setEditable:NO] ;
				[commentField setEditable:NO] ;
				
				[commentField selectText:self];
				//[[commentField currentEditor] setSelectedRange:NSMakeRange([[commentField stringValue] length], 0)];
				//[commentField setEnabled:NO];
				//[commentField setEnabled:YES];
				[self toggleRecord] ;
			}
			if([watchAnotherButtonView hitTest:loc]) {
				[nameField setSelectable:NO] ;
				[emailField setSelectable:NO] ;
				[commentField setSelectable:NO] ;
				
				NSString *Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kWatchSelectedImage];
				NSURL *url   = [NSURL fileURLWithPath:Lpath];
				[watchAnotherButtonView setImage:url] ;
				
				if ([recordTimer isValid]) {
					[recordTimer invalidate] ;
					recordTimer = nil ;
					[recordTimer release] ;
				}
				if(commenting) {
					[self saveFeedbackLogEntry];
				}
				[self startFinishTimer] ;
			} // end if hittest
			
			if ([emailField hitTest:loc]) {
				//if(kDebug) NSLog(@"Gots me a hit on email") ;
			}
		} // end if can eddit
	//}
}

/*
- (void)mouseDown:(NSEvent *)event
{
	//
	if(!kRotate) {
		NSPoint  loc = [self convertPoint: [event locationInWindow] fromView: nil];	
		//CGPoint cgloc = NSPointToCGPoint(loc) ;
		
		if(canEdit) {
			if([recordButtonView hitTest:loc]) {
				
				[commentField selectText:self];
				
				//[[commentField currentEditor] setSelectedRange:NSMakeRange([[commentField stringValue] length], 0)];
				[commentField setEnabled:NO];
				[commentField setEnabled:YES];
				[[self window] makeFirstResponder:self] ;
				[self toggleRecord] ;
			}
			if([watchAnotherButtonView hitTest:loc]) {
				NSString *Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kWatchSelectedImage];
				NSURL *url   = [NSURL fileURLWithPath:Lpath];
				[watchAnotherButtonView setImage:url] ;
				
				if ([recordTimer isValid]) {
					[recordTimer invalidate] ;
					recordTimer = nil ;
					[recordTimer release] ;
				}
				if(commenting) {
					[self saveFeedbackLogEntry];
				}
				[self startFinishTimer] ;
			} // end if hittest
			
			if ([emailField hitTest:loc]) {
				if(kDebug) NSLog(@"Gots me a hit on email") ;
			}
		} // end if can eddit
	}
}

*/

#pragma mark timers
- (void) startFinishTimer {
	
	if(canEdit) {
		canEdit = NO ; // stop user from editing
		
		NSString *Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kWatchSelectedImage];
		NSURL *url   = [NSURL fileURLWithPath:Lpath];
		[watchAnotherButtonView setImage:url] ;
		
		if(isRecording) {
			[recordView stopRecording] ; // stop recording
			
			[self stopRecordTimer] ;
			
			Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kRecordGreenImage];
			url   = [NSURL fileURLWithPath:Lpath];
			[recordButtonView setImage:url] ;
			isRecording = NO ;
		}
		
		if ([recordTimer isValid]) {
			[recordTimer invalidate] ;
			recordTimer = nil ;
			[recordTimer release] ;
		}
		recordTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:0.125]
											   interval:0.1	 
												 target: self
											   selector: @selector(watchAnotherTimerMethod:)
											   userInfo: nil
												repeats: NO];
		
		[[NSRunLoop currentRunLoop] addTimer:recordTimer forMode:NSDefaultRunLoopMode];
		
	}
	
}



-(void) watchAnotherTimerMethod:(NSTimer*)timer {
	[self delegatedMethod] ;
	NSString *Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kWatchUnselectedImage];
	NSURL *url   = [NSURL fileURLWithPath:Lpath];
	[watchAnotherButtonView setImage:url] ;
	
	[self recordTimerMethod:nil] ;
	
	timeValue = kRecordTime ;
	editing = NO ;
	commenting = NO ;
	isRecording = NO ;
	canEdit = YES ; // turn on user editing
	
	[nameField setTitleWithMnemonic:@"Name"] ;
	[emailField setTitleWithMnemonic:@"Email"]; 
	[commentField setTitleWithMnemonic:@"Comments"] ;
}


-(void) recordTimerMethod:(NSTimer*)timer {
	
	NSString *time = [NSString stringWithFormat:@"%d", timeValue] ;
	[countdownView setText:time] ;
	
	if (timeValue <= 0) {
		//[self stopRecordingAndReturn] ;
		[self startFinishTimer] ;
	}
	timeValue -- ;
}

-(void) startRecordTimer {
	if ([recordTimer isValid]) {
		[recordTimer invalidate] ;
		recordTimer = nil ;
		[recordTimer release] ;
	}
	timeValue = kRecordTime ;
	
	recordTimer =  [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:1.0]
												interval:1.0	 
												  target: self
												selector: @selector(recordTimerMethod:)
												userInfo: nil
												 repeats: YES];
	
	[[NSRunLoop currentRunLoop] addTimer:recordTimer forMode:NSDefaultRunLoopMode];
	
	

}

-(void) stopRecordTimer {
	if ([recordTimer isValid]) {
		[recordTimer invalidate] ;
		recordTimer = nil ;
		[recordTimer release] ;
	}
	timeValue = kRecordTime ;
}


- (void) toggleRecord {
	
	if(canEdit) {
		if (!isRecording) {
			NSString *Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kRecordRedImage];
			NSURL *url   = [NSURL fileURLWithPath:Lpath];
			[recordButtonView setImage:url] ;
			isRecording = YES ;
			[self startRecordTimer] ;
			
			
			//Get the date and time to use in the feedback log and name movie file
			NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
			[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
			[dateFormatter setDateStyle:NSDateFormatterShortStyle];
			NSDate *date = [NSDate date];
			NSString* day = [dateFormatter stringFromDate:date];
			day = [day stringByReplacingOccurrencesOfString:@":" withString:@""];
			NSString* name = [nameField stringValue];
			
			NSString *recordPath = [NSString stringWithFormat:@"%@%@%@%@%@%@.mov", kMovieRecordPath, currentMovieName, @" ", name, @" ", day];
			[self setPathToRecordTo:recordPath];
			[recordView startRecording:recordPath ] ; // start recording
			[dateFormatter release] ;
		} else {
			
			[self stopRecordTimer] ;
			NSString *Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kRecordGreenImage];
			NSURL *url   = [NSURL fileURLWithPath:Lpath];
			[recordButtonView setImage:url] ;
			//isRecording = NO ;
			[self saveFeedbackLogEntry] ;
			[self setPathToRecordTo: @"no video recorded"];
			[self startFinishTimer] ;
		}
	}
}

#pragma mark Text input handling
- (BOOL) isEditing {
	
	return editing ;
}

- (BOOL) isCommenting {
	
	return commenting ;
}

- (void)controlTextDidBeginEditing:(NSNotification *)aNotification
{
    if([aNotification object] == nameField)
    {
		//if(kDebug) NSLog(@"The contents of the text field changed in name field") ;
		
		commenting = NO ;
		editing = YES ;
		[nameField setStringValue:@" "] ;
		
		[[nameField currentEditor] setSelectedRange:NSMakeRange(0, [[nameField stringValue] length])];
		
		
		
    }
	if([aNotification object] == emailField)
    {
		//if(kDebug) NSLog(@"The contents of the text field changed in name emailField");
		
		commenting = NO ;
		editing = YES ;
		[emailField setStringValue:@" "] ;
		[[emailField currentEditor] setSelectedRange:NSMakeRange(0, [[nameField stringValue] length])];
		
    }
	if([aNotification object] == commentField)
    {
      // if(kDebug) NSLog(@"The contents of the text field changed in name commentField");
		
		commenting = YES ;
		editing = YES ;
		[commentField setStringValue:@" "] ;
		[[commentField currentEditor] setSelectedRange:NSMakeRange(0, [[commentField stringValue] length])];
		
    }
}



#pragma mark Setup
- (void) setupLayers {
	NSRect pRect ;
	
	CGFloat windowWidth = [self bounds].size.width;
	CGFloat windowHeight = [self bounds].size.height;
	
	float fontSize = windowHeight*0.04 ;
	NSFont* font = [NSFont fontWithName:@"Arial" size:fontSize];
	NSColor *fontColor = [NSColor grayColor] ;
	
	float entryFieldsWidth = windowWidth*0.5;
	CGFloat entryFieldsXPos =  windowWidth*0.501;
	CGFloat entryFieldsYPos =  windowHeight*0.559;
	CGFloat entryFieldSeperator = windowHeight*0.02; 
	
	// Name FIELD
	float nameHeight =  fontSize*1.38;
	float nameWidth = entryFieldsWidth;
	CGPoint namePos = CGPointMake(entryFieldsXPos, entryFieldsYPos) ;

	pRect = NSMakeRect(namePos.x, namePos.y, nameWidth, nameHeight) ;
	nameField = [[NSTextField alloc] initWithFrame:pRect] ;
	[nameField setBezeled:YES] ;
	[nameField setFont:font] ;
	[nameField setTextColor:fontColor] ;
	[nameField setTitleWithMnemonic:@"Name"] ;
	[nameField setDelegate:self] ;
	[[nameField cell] setWraps:YES] ;
	[self addSubview:nameField] ;
	
	//update y pos
	entryFieldsYPos = entryFieldsYPos - nameHeight - entryFieldSeperator;
	
	// EMAIL FIELD
	float emailHeight =  nameHeight;
	float emailWidth = entryFieldsWidth;
	CGPoint emailPos = CGPointMake(entryFieldsXPos, entryFieldsYPos) ;
		
	pRect = NSMakeRect(emailPos.x, emailPos.y, emailWidth, emailHeight) ;
	emailField = [[NSTextField alloc] initWithFrame:pRect] ;
	[emailField setBezeled:YES] ;
	[emailField setFont:font] ;
	[emailField setTextColor:fontColor] ;
	[emailField setTitleWithMnemonic:@"Email"]; 
	[emailField setDelegate:self] ;
	[[emailField cell] setWraps:YES] ;
	[self addSubview:emailField] ;
	
	
	// COMMENT FIELD
	CGPoint commentPos = CGPointMake(entryFieldsXPos, windowHeight*0.168) ;
	float commentHeight = fontSize*3.3;
	float commentWidth = entryFieldsWidth ;
	
	// comment entry text field
	pRect = NSMakeRect(commentPos.x, commentPos.y, commentWidth, commentHeight) ;
	commentField = [[NSTextField alloc] initWithFrame:pRect] ;
	[commentField setBezeled:YES] ;
	[commentField setFont:font] ;
	[commentField setTextColor:fontColor] ;
	[commentField setTitleWithMnemonic:@"Write your comments and press ENTER"] ;
	[commentField setDelegate:self] ;
	[self addSubview:commentField] ;
	
	
	// record capture view
	float rWidth = [self bounds].size.width*0.495 ;
	float rHeight = ((rWidth*9)/16);
	
	CGPoint recPos = CGPointMake([self bounds].size.width*0.503, [self bounds].size.height*0.69) ;
	pRect = NSMakeRect(recPos.x, recPos.y, rWidth, rHeight) ;
	recordView = [[JigSawQTRecordView alloc] initWithFrame:pRect] ;
	[self addSubview:recordView] ;
	
	// countdown view
	pRect = NSMakeRect([self bounds].size.width*0.408, [self bounds].size.height*0.712, 
					   [self bounds].size.width*0.065, [self bounds].size.height*0.052) ;
	countdownView = [[JigSawCountDownView alloc] initWithFrame:pRect] ;
	NSString *time = [NSString stringWithFormat:@"%d", kRecordTime] ;
	[countdownView setText:time] ;
	[self addSubview:countdownView] ;
	
	// record button view
	NSString *Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kRecordGreenImage];
	NSURL *url   = [NSURL fileURLWithPath:Lpath];
	pRect = NSMakeRect([self bounds].size.width*0.499, [self bounds].size.height*0.32, // x, y pos
					   [self bounds].size.width*0.5, [self bounds].size.height*0.14) ; // width, height
	recordButtonView = [[JigSawImageButtonView alloc] initWithImage:pRect name:url] ;
	[self addSubview:recordButtonView] ;
	
	// click to watch another view
	Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kWatchUnselectedImage];
	url   = [NSURL fileURLWithPath:Lpath];
	pRect = NSMakeRect([self bounds].size.width*0.499, [self bounds].size.height*0.0, 
					   [self bounds].size.width*0.5, [self bounds].size.height*0.14) ;
	watchAnotherButtonView = [[JigSawImageButtonView alloc] initWithImage:pRect name:url] ;
	[self addSubview:watchAnotherButtonView] ;
	
	//Submit button
	pRect = NSMakeRect(00, 0, 150, 100) ;
	// create the push button that allows us to record or stop/save feedback video
    submitButton = [[NSButton alloc] initWithFrame:pRect];
    [submitButton setTarget:self];
    [submitButton setAction:@selector(saveFeedbackLogEntry:)];
    [submitButton setAutoresizingMask:NSViewWidthSizable|NSViewMinXMargin|NSViewMinYMargin];
    [submitButton setBordered:YES];
    [submitButton setEnabled:YES];
    [submitButton setButtonType:NSMomentaryLightButton];
    [submitButton setBezelStyle:NSSmallSquareBezelStyle]; // NSSmallSquareBezelStyle NSRecessedBezelStyle
    [submitButton setTitle:@"Submit"];
	[submitButton setImagePosition:NSNoImage];
    //[submitButton setTag:tag];
    [[submitButton cell] setControlSize:NSMiniControlSize];
    //[self addSubview:submitButton];
 
}


-(void) saveFeedbackLogEntry{

	//TODO get the name of the video that was watched
	NSString* videoWatched = currentMovieName ;
	
	NSString* comments = [commentField stringValue]; 
	
	NSString* name = [nameField stringValue];
	
	NSString* emailAddress = [emailField stringValue];
	//emailAddress = [emailAddress stringByReplacingOccurrencesOfString:@" " withString:@""];
	
	//Get the date and time to use in the feedback log and name movie file
	NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
	[dateFormatter setDateStyle:NSDateFormatterShortStyle];
	NSDate *date = [NSDate date];
	NSString* day = [dateFormatter stringFromDate:date];
	[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
	//NSString* dateAndTime = [dateFormatter stringFromDate:date];
	
	//Initialize the FileHandler and Write file entry for this feedback
	outputDirectoryPath = @"/Users/Shared/Kiosk/Data/"; //This can be initialized from the config file when self is created. TODO
	NSString* outputFilename = [NSString stringWithFormat:@"%@.txt", day];
	JigSawKioskTextOutput* feedbackLogWriter = [[JigSawKioskTextOutput alloc] initWithDirectoryPath:outputDirectoryPath 
																				   AndFileToWriteTo:outputFilename];
	
	NSString *videoFilename = [self pathToRecordTo];
	[feedbackLogWriter recordFeedbackInformationToFile:videoWatched 
												 dateWatched:day
											   nameOfWatcher:name
									   emailAddressOfWatcher:emailAddress
								  writtenFeedbackFromComment:comments 
									   FeedbackVideoFilename:videoFilename];
		
	
	
	//Send the thank you email, Note: all message details except recipient (SMTP, message content etc currently hardcoded into FeedbackEmailSender)
	FeedbackEmailSender *feedbackEmail = [[FeedbackEmailSender alloc] init];
	[feedbackEmail sendEmailMessageTo:name AtEmail:emailAddress];
	[dateFormatter release] ;
	[feedbackLogWriter release] ;
	[feedbackEmail release] ;
	
}


/* ---------------------------------
 Getter and Setter Methods
 ---------------------------------*/

@synthesize commentLabel;
@synthesize commentField;
@synthesize nameField;
@synthesize emailLabel;
@synthesize emailField;
@synthesize recordView;
@synthesize submitButton;
@synthesize outputDirectoryPath;
@synthesize countdownView ; 
@synthesize recordButtonView, watchAnotherButtonView ;
@synthesize currentMovieName ;

-(NSString*) pathToRecordTo {
	return pathToRecordTo;
}

-(void) setPathToRecordTo: (NSString*) aPath {
	[aPath retain];
	[pathToRecordTo release];
	pathToRecordTo = aPath;
	[pathToRecordTo retain];
}

- (void) dealloc {
	[countdownView release] ;
	[recordButtonView release] ;
	[watchAnotherButtonView release] ;
	[pathToRecordTo release];
	[super dealloc]; 
}
@end
